<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="treeName"
            placeholder="请输入分类名称"
            clearable
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="treeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            @node-click="handleNodeClick"
            :highlight-current="true"
            node-key="id"
            :default-expanded-keys="defaultExpandkeys"
            accordion
          />
        </div>
      </el-col> -->
      <el-col>
        <!-- <el-col :span="20" :xs="24"> -->
        <el-form
          :model="queryParams"
          ref="queryForm"
          v-show="showSearch"
          :inline="true"
        >
          <el-form-item label="关键字" prop="name">
            <el-input
              v-model="queryParams.keywords"
              placeholder="请输入手机号/姓名"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              v-hasPermi="['11310']"
              @click="handleAdd"
              >添加管理员</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="tableList" :border="true">
          <el-table-column
            label="管理员"
            prop="adminName"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="登录账号"
            prop="userName"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="所属部门"
            prop="department"
            align="center"
          ></el-table-column>
          <el-table-column label="手机号" prop="phone" align="center" />
          <el-table-column
            label="角色"
            prop="role"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="状态" align="center" key="enable" width="100">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enable"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="设置时间"
            align="center"
            prop="addTime"
            width="180"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.addTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
            width="100"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['11320']"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['11330']"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['11350']"
                @click="handleLog(scope.row)"
                >登录日志</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.currentPage"
          :limit.sync="queryParams.pagesize"
          @pagination="getList"
        />
      </el-col>
      <!-- 添加或修改角色配置对话框 -->
      <el-dialog
        :title="title"
        :visible.sync="open"
        width="500px"
        append-to-body
      >
        <!-- *姓名、*账号、*部门（树状）、*手机号、*角色（下拉） -->
        <!-- *管理员姓名、*登录账号、登录密码、*所属部门（树状下拉框）、*手机号、*角色（下拉框） -->
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          :validate-on-rule-change="false"
          label-width="100px"
        >
          <el-form-item label="管理员姓名" prop="adminName">
            <el-input v-model="form.adminName" placeholder="请输入管理员姓名" />
          </el-form-item>
          <el-form-item label="登录账号" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入登录账号" />
          </el-form-item>
          <el-form-item
            label="登录密码"
            prop="password"
            style="margin-bottom: 0"
          >
            <el-input
              v-model="form.password"
              placeholder="请输入登录密码"
              type="password"
              maxlength="20"
              show-password
            />
            <span class="warning">不修改密码时，请勿输入内容</span>
          </el-form-item>
          <el-form-item label="所属部门" prop="deptId">
            <treeselect
              v-model="form.deptId"
              :options="treeOptions"
              :show-count="true"
              placeholder="请选择所属部门"
              @select="selectDepart"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="form.phone"
              placeholder="请输入手机号"
              maxlength="11"
            />
          </el-form-item>
          <el-form-item label="角色" prop="roleId">
            <el-select
              v-model="form.roleId"
              placeholder="请选择"
              @change="changeroleName"
            >
              <el-option
                v-for="item in roleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分配权限" prop="menuIds">
            <el-checkbox
              v-model="menuExpand"
              @change="handleCheckedTreeExpand($event, 'menu')"
              >展开/折叠</el-checkbox
            >
            <el-checkbox
              v-model="menuNodeAll"
              @change="handleCheckedTreeNodeAll($event, 'menu')"
              >全选/全不选</el-checkbox
            >
            <el-checkbox
              v-model="menuCheckStrictly"
              @change="handleCheckedTreeConnect($event, 'menu')"
              >父子联动</el-checkbox
            >
            <el-tree
              class="tree-border"
              :data="menuOptions"
              show-checkbox
              ref="menu"
              node-key="thecode"
              :check-strictly="!menuCheckStrictly"
              empty-text="加载中，请稍后"
              :props="defaultProps"
            ></el-tree>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 登录日志 -->
      <el-dialog
        title="登录日志"
        :visible.sync="open2"
        width="900px"
        append-to-body
      >
        <el-row :gutter="10" class="mb8">
          <el-form
            :model="adminParams"
            ref="adminParams"
            v-show="showSearch"
            :inline="true"
          >
            <el-form-item label="管理员" prop="status">
              <el-select
                v-model="adminParams.userId"
                placeholder="管理员"
                clearable
                size="small"
                style="width: 200px"
              >
                <el-option
                  v-for="dict in adminOptions"
                  :key="dict.theid"
                  :label="dict.adminName"
                  :value="dict.theid"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="登录时间">
              <el-date-picker
                v-model="dateRange"
                size="small"
                style="width: 220px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery2"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery2"
                >重置</el-button
              >
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                >导出</el-button
              >
            </el-form-item>
          </el-form>
        </el-row>
        <el-table
          v-loading="loading2"
          :data="tableList2"
          :border="true"
          max-height="600px"
        >
          <el-table-column
            label="管理员姓名"
            prop="adminName"
            align="center"
            :show-overflow-tooltip="true"
            width="160"
          />
          <el-table-column
            label="角色"
            prop="role"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="登录IP"
            prop="loginIp"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="登录时间" align="center" prop="createTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.loginTime) }}</span>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="adminTotal > 0"
          :total="adminTotal"
          :page.sync="adminParams.currentPage"
          :limit.sync="adminParams.pagesize"
          @pagination="getLogList"
        />
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
import {
  getPage,
  listData,
  addData,
  getData,
  updateData,
  delData,
  getSelect,
  changeEnable,
  getLogPage,
  logListData,
} from "@/api/system/adminSet";
import { getData as getRoleData } from "@/api/system/adminRole";
import { getJurisdictionInfo } from "@/api/common";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "adminSet",
  data() {
    return {
      treeName: undefined,
      treeOptions: [],
      currentId: null,
      defaultExpandkeys: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      queryParams: {
        currentPage: 1,
        pagesize: 10,
        ascriptionId: undefined,
        deptId: undefined,
        keywords: undefined,
      },
      loading: true,
      tableList: [],
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: "",
      open: false,
      form: {},
      rules: {
        adminName: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        userName: [
          { required: true, message: "账号不能为空", trigger: "blur" },
        ],
        password: [
          // { required: true, message: "登录密码不能为空", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "登录密码长度必须介于 2 和 20 之间",
            rigger: "blur",
          },
        ],
        deptId: [
          { required: true, message: "所属部门不能为空", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
      roleOptions: [],
      open2: false,
      loading2: true,
      tableList2: [],
      adminParams: {
        currentPage: 1,
        pagesize: 10,
        userId: undefined,
      },
      adminOptions: [],
      adminTotal: 0,
      dateRange: [],
      showSearch: true,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        // headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        // url: process.env.VUE_APP_BASE_API + "/system/user/importData",
        url: "",
      },
      /** 分配权限 */
      menuCheckStrictly: true,
      menuExpand: false,
      menuNodeAll: false,
      // 菜单列表
      menuOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  components: {
    Treeselect,
  },
  watch: {
    // 根据名称筛选树
    treeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    // this.getPageInfo();
    this.getTree();
    this.getList();
    this.getSelect();
    this.getMenuTreeselect();
  },
  mounted() {},
  methods: {
    getPageInfo() {
      getPage(this.queryParams).then((response) => {
        this.treeOptions = response.result.data;
        this.currentId = response.result.data[0].id;
        this.deptName = response.result.data[0].label;
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(this.currentId, true, false);
        });
        this.getList();
      });
    },
    getTree() {
      getPage(this.queryParams).then((response) => {
        this.treeOptions = response.result.data;
      });
    },
    getList() {
      this.loading = true;
      // this.queryParams.deptId = this.currentId;
      listData(this.queryParams).then((response) => {
        this.tableList = response.result.rows;
        this.total = response.result.total;
        this.loading = false;
      });
    },
    getSelect() {
      getSelect().then((response) => {
        this.roleOptions = response.result.role; //角色
      });
    },
    handleNodeClick(data) {
      this.currentId = data.id;
      this.deptName = data.label;
      this.getList();
    },
    handleQuery() {
      this.queryParams.currentPage = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    handleUpdate(row) {
      this.reset();
      const theId = row.theid;
      getData(theId).then((response) => {
        this.form = response.result;
        console.log("this.form--", this.form);
        this.form.deptName = row.department;
        this.form.roleName = row.role;
        this.open = true;
        // 获取当前用户 对应的权限
        if (response.result.menuIds != null) {
          this.$nextTick(() => {
            let checkedKeys = response.result.menuIds.split(",").map((ele) => {
              return Number(ele);
            });
            checkedKeys.forEach((v) => {
              this.$nextTick(() => {
                this.$refs.menu.setChecked(v, true, false);
              });
            });
          });
        }
        this.title = "修改";
      });
    },
    submitForm() {
      let checkedNodes = this.getMenuAllCheckedNodes();
      this.form.jurisdiction = checkedNodes[0].join(",");
      this.form.menuIds = checkedNodes[1].join(",");
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.theid != undefined) {
            updateData(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addData(this.form).then((response) => {
              this.msgSuccess("添加成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    resetMenu() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false;
      this.menuNodeAll = false;
      this.menuCheckStrictly = true;
    },
    reset() {
      this.resetMenu();
      this.form = {
        adminName: undefined,
        userName: undefined,
        password: undefined,
        deptId: this.currentId,
        deptName: this.deptName,
        roleId: undefined,
        roleName: undefined,
        phone: undefined,
        jurisdiction: undefined,
        menuIds: undefined,
      };
      this.resetForm("form");
    },
    handleDelete(row) {
      const theId = row.theid;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口
          return delData(theId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    handleStatusChange(row) {
      console.log("row.enable--1--", row.enable);
      let text = row.enable === 1 ? "启用" : "停用";
      this.$confirm('是否确认' + text + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口 改变状态值
          return changeEnable(row.theid, row.enable);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.enable = row.enable === 1 ? 0 : 1;
          console.log("row.enable--2--", row.enable);
        });
    },
    handleExport() {
      // const queryParams = this.queryParams;
      this.$confirm("是否确认导出?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口导出表
          // return exportRole(queryParams);
        })
        .then((response) => {
          // this.download(response.msg);
        });
    },
    handleLog(row) {
      this.adminParams.userId = row.theid;
      this.getLogPage();
      this.open2 = true;
      this.getLogList();
    },
    getLogPage() {
      getLogPage(this.adminParams).then((response) => {
        this.adminOptions = response.result.admin; //管理员下拉框
        this.getLogList();
      });
    },
    getLogList() {
      this.loading2 = false;
      if (this.dateRange != null) {
        this.adminParams.startTime = this.dateRange[0];
        this.adminParams.endTime = this.dateRange[1];
      }
      logListData(this.adminParams).then((response) => {
        this.tableList2 = response.result.rows;
        this.adminTotal = response.result.total;
        this.loading2 = false;
      });
    },
    handleQuery2() {
      this.adminParams.currentPage = 1;
      this.getLogList();
    },
    resetQuery2() {
      this.dateRange = [];
      this.adminParams.userId = undefined;
      this.resetForm("adminParams");
      this.handleQuery2();
    },
    selectDepart(val) {
      if (this.treeOptions.length > 0) {
        this.form.deptName = val.label;
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    getMenuTreeselect() {
      getJurisdictionInfo().then((response) => {
        this.menuOptions = response.result;
        console.log("menuOptions---", this.menuOptions);
      });
    },
    // 下拉框切换角色，分配权限里，动态显示角色所对应权限
    changeroleName(e) {
      this.resetMenu();
      if (this.roleOptions.length > 0) {
        this.form.roleName = e
          ? this.roleOptions.find((ele) => ele.value === e).label
          : "";
        this.form.roleId = e;
        getRoleData(e).then((response) => {
          if (response.result.menuIds != null) {
            this.$nextTick(() => {
              let checkedKeys = response.result.menuIds
                .split(",")
                .map((ele) => {
                  return Number(ele);
                });
              // console.log('checkedKeys---',checkedKeys)
              checkedKeys.forEach((v) => {
                this.$nextTick(() => {
                  this.$refs.menu.setChecked(v, true, false);
                });
              });
            });
          }
        });
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      let treeList = this.menuOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      this.menuCheckStrictly = value ? true : false;
    },
    // 所有菜单节点数据 Keys
    /* getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    }, */
    // 所有菜单节点数据 Nodes
    getMenuAllCheckedNodes() {
      // 目前被选中的菜单节点
      let checkedNodes = this.$refs.menu.getCheckedNodes();
      // 半选中的菜单节点
      let halfCheckedNodes = this.$refs.menu.getHalfCheckedNodes();
      checkedNodes.unshift.apply(checkedNodes, halfCheckedNodes);
      let jurArr = [],
        menuIdarr = [];
      checkedNodes.forEach((item, index) => {
        jurArr.push(item.label);
        menuIdarr.push(item.thecode);
      });
      return [jurArr, menuIdarr];
    },
  },
};
</script>

<style scoped lang="scss">
// /deep/
/* /deep/ .el-form-item__label:before {
  content: '' !important;
} */
.warning {
  color: red;
  font-size: 12px;
}
</style>